//
//  Settings.m
//  Truffle
//
//  Created by Averbouch David on 05/03/10.
//  Copyright 2010 Averbouch. All rights reserved.
//

#import "CommentsAdd.h"
#import "DAOTruffle.h"


@implementation CommentsAdd
@synthesize commentaire, pseudo, moment, champtxt, comm, pref, idServ, ipServ;
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Commenter";
	self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];

	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
											  initWithBarButtonSystemItem:UIBarButtonSystemItemStop 
											  target:self action:@selector(cancel_Clicked:)] autorelease];
	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
											   initWithBarButtonSystemItem:UIBarButtonSystemItemAction
											   target:self action:@selector(save_Clicked:)] autorelease];
	


	// Recuperation de l'heure mais ne sert en realité plus a rien
	[moment setText: [self jourHeure]];
	moment.textColor = [UIColor colorWithRed:80.0f/255.0f green:89.0f/255.0f blue:111.0f/255.0f alpha:1.0f];
	moment.shadowColor = [UIColor colorWithRed:0/255 green:0/255 blue:0/255 alpha:0.4];
	moment.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
	NSLog(@"AddComments ---- Heure recuperé : %@", moment.text);
	
}

- (void) viewWillAppear:(BOOL)animated
{
	dao = [DatasTruffle getDao];
	
	// Recuperation de mon pseudo
	NSString *user = [[dao getInfoSelf] objectForKey:@"pseudo"];
	NSLog(@"username -------> %@", user);
	if (user == nil) {
		user=@"Truffle_User";
	}
	
	[pseudo setText: user];
	pseudo.textColor = [UIColor colorWithRed:80.0f/255.0f green:89.0f/255.0f blue:111.0f/255.0f alpha:1.0f];
	pseudo.shadowColor = [UIColor colorWithRed:0/255 green:0/255 blue:0/255 alpha:0.4];
	pseudo.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
	NSLog(@"AddComments ---- Pseudo recuperé : %@", pseudo.text);
}

- (void) viewDidAppear:(BOOL)animated{
	//Forcer l ouverture du clavier
	[commentaire becomeFirstResponder];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void) cancel_Clicked:(id)sender 
{
	[commentaire setText:@""];
	NSLog(@"AddComments ---- Fermeture");
	[self.navigationController dismissModalViewControllerAnimated:YES];
}

//Bouton saved
- (void) save_Clicked:(id)sender 
{	
	NSMutableString *addr = [[NSMutableString alloc] initWithFormat:@"%@/iphone/comment/add/", ipServ];
	NSString *com = [NSString stringWithFormat:@"%@", commentaire.text];
	NSString *post = [NSString stringWithFormat:@"idService=%@&pseudo=%@&content=%@", idServ, pseudo.text, [self urlEncodeValue:com]];
	NSData *msgEncode = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	NSLog(@"AddComments ---- Envoie a : %@\n", addr);
	
	NSURL *url = [[NSURL alloc] initWithString:addr];
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
	[request setURL:url];
	[request setHTTPMethod:@"POST"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:msgEncode];
	
	NSHTTPURLResponse *urlResponse = nil;
	NSError *error = [[NSError alloc] init];
	NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
	NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	[addr release];
	[request release];
	[url release];
	
	NSLog(@"AddComments ---- Reponse : %@", result);

	if ([result isEqualToString:@"OK"]) result = [NSString stringWithFormat:@"%@, Send Succeed", result];
	else if ([result isEqualToString:@"KO"]) result = [NSString stringWithFormat:@"%@, Send Failed !!!", result]; 
	else result = [NSString stringWithFormat:@"Server Error, Send Failed !!!", result];
	
	[error release];
	
	[commentaire setText:@""];
	NSLog(@"AddComments ---- Fermeture");
	[self.navigationController dismissModalViewControllerAnimated:YES];
}

- (NSString *)urlEncodeValue:(NSString *)str
{
	NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("?=&+<>/\\"), kCFStringEncodingUTF8);
	return [result autorelease];
}
	 
- (NSString *) jourHeure {
	
	//Obtention de la date courante (jour/mois - heure/minute)
	NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];;
	NSDate *today = [NSDate date];
	NSDateComponents *comps = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit) fromDate:today];
	NSInteger day = [comps day];
	NSInteger month = [comps month];
	NSInteger minute = [comps minute];
	NSInteger hour = [comps hour];	
	NSString *j = @"";
	if (day < 10)
		j = [NSString stringWithFormat: @"0%d", day]; 
	else j = [NSString stringWithFormat: @"%d", day];
	NSString *m = @"";
	if (month < 10)
		m = [NSString stringWithFormat: @"0%d", month]; 
	else m = [NSString stringWithFormat: @"%d", month];
	NSString *h = @"";
	if (hour < 10)
		h = [NSString stringWithFormat: @"0%d", hour]; 
	else h = [NSString stringWithFormat: @"%d", hour];
	NSString *mn = @"";
	if (minute < 10)
		mn = [NSString stringWithFormat: @"0%d", minute]; 
	else mn = [NSString stringWithFormat: @"%d", minute];
	NSString *tps = [NSString stringWithFormat: @"%@h%@ (le %@/%@)", h, mn, j, m];
	[gregorian release];
	return tps;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[commentaire release];
	[pseudo release];
	[moment release];
}


@end
